package com.hlw.core;

 
import java.util.ArrayList;
import java.util.List;

import com.hlw.entity.Menu;
 
//用List构建带有层次结构的json数据
//List父子节点构造树形Json
public class TreeUtil {
    //将list集合转成树形结构的list集合
    public static List<Menu> listToTree(List<Menu> list) {
        //用递归找子。
        List<Menu> treeList = new ArrayList<Menu>();
        for (Menu tree : list) {
            if (tree.getPid().equals("0")) {
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }
 
    //寻找子节点
    private static Menu findChildren(Menu tree, List<Menu> list) {
        for (Menu node : list) {
            if (node.getPid().equals(tree.getId())) {
                if (tree.getChildrens() == null) {
                    tree.setChildrens(new ArrayList<Menu>());
                }
                tree.getChildrens().add(findChildren(node, list));
            }
        }
        return tree;
    }
 
}